同樣根據以上的Reqres API 來示範
首先一樣根據Response 建立Model
User.swift
:
struct UserGetResponse: Decodable {
let page : Int
let perPage : Int
let total: Int
let totalPages : Int
let data : [User]
}
struct User : Decodable, Hashable {
let id : Int
let email : String
let firstName : String
let lastName : String
let avatar : String
}
接著在UserURLSession.swift
處理關於URLSession
的事件
func userGetRequest(page: Int, completionHandler: @escaping (UserGetResponse) -> Void) {
let url = URL(string: "https://reqres.in/api/users?page=\(page)")!
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) {
data, response, error in
if let data = data {
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let response = try decoder.decode(UserGetResponse.self, from: data)
completionHandler(response)
}catch(let error) {
print(error.localizedDescription)
}
} else {
print("No Data")
}
}.resume()
}
之後在View 設計畫面並使用GETSampleView.swift
:
import SwiftUI
struct GETSampleView: View {
@State private var users: [User] = []
var body: some View {
NavigationView {
VStack {
Button {
UserURLSession.shared.userGetRequest(page: 1) { response in
DispatchQueue.main.async {
users = response.data
}
}
} label: {
Text("GET Request")
}
ScrollView {
LazyVStack {
ForEach(users, id: \.self) { user in
UserItemView(user: user)
}
}
}
.cornerRadius(8)
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle(Text("URLSession GET Sample"))
}
}
}
struct GETSampleView_Previews: PreviewProvider {
static var previews: some View {
GETSampleView()
}
}
這邊所有URLSession 的範例一起放在Github: URLSessionSample 供大家參考